<template>
  <div class="products-page">
    <a-button type="primary" shape="round" size="large" @click="navigateToCreateProduct" class="create-product-button">
      <template #icon>
        <PlusOutlined />
      </template>
      新建商品
    </a-button>
    <h1 class="page-title">商品列表</h1>
    <div class="products-grid">
      <ProductCard v-for="product in products" :key="product.id" :product="product" @refresh="getProducts" />
    </div>
  </div>
</template>

<script>
import BusProdCard from './bus_card/BusProdCard.vue'; // 引入商品卡片组件
// import productsData from './productsData'; // 引入示例数据
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import request from '../../util/request';
import defaultPicture from '../../assets/default.jpg';

export default {
  name: 'BusProdList',
  components: {
    ProductCard: BusProdCard,
  },
  setup() {

    const products = ref({
      id: 0,
      prodName: '',
      prodPrice: '',
      prodCount: '',
      prodCaption: '',
      prodPicture: '',
    });

    const router = useRouter();

    onMounted(() => {
      console.log('商品列表页面挂载');
      getProducts();
    });

    const getProducts = () => {
      request.post('product/getMyProd', {
        busid: sessionStorage.getItem('userid'),
      }).then(res => {
        products.value = res.data;
        products.value.forEach(product => {
          if (product.prodPicture === null) {
            product.prodPicture = defaultPicture;
          }
        });
      }).catch(err => {
        console.log(err);
        message.error('获取商品列表失败' + err);
      });
    };

    const navigateToCreateProduct = () => {
      router.push({ name: 'CreateProd' });
    };

    return {
      products,
      getProducts,
      navigateToCreateProduct,
    };
  }
};
</script>

<style src="../../assets/styles/busProdList.css" scoped></style>
